package com.wsz.logistic.service.impl;

import com.wsz.logistic.bean.Code;
import com.wsz.logistic.common.exception.RTException;
import com.wsz.logistic.mapper.CodeMapper;
import com.wsz.logistic.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class CodeServiceImpl implements CodeService {
    @Autowired
    private CodeMapper codeMapper;

    @Override
    public void saveCode(Code code) {
        Date date = new Date();
        date.setMinutes(date.getMinutes() + 5);
        code.setExpires(date);
        codeMapper.insertSelective(code);
    }

    @Override
    public boolean checkCode(Code code) {
        Code c = codeMapper.selectByPrimaryKey(code.getUuid());
        if (c == null) {
            throw new RTException("验证码不存在");
        }
        if (!c.getCode().equalsIgnoreCase(code.getCode())) {
            throw new RTException("验证码错误");
        }
        if (c.getExpires().getTime() < System.currentTimeMillis()) {
            throw new RTException("验证码失效");
        }
        codeMapper.deleteByPrimaryKey(code.getUuid());
        return true;
    }
}
